<?php

namespace App\Console;

use App\Http\Controllers\Wechat;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\DB;
use EasyWeChat\Foundation\Application;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')
        //          ->hourly();

        $schedule->call(function () {
            date_default_timezone_set('PRC');
            $today = strtotime(date('Y-m-d', time()));
            $before_days_num = 1;
            $before_days_end = $before_days_num + 1;
            $three_days_later = date('Y-m-d H:i:s', strtotime('+' . $before_days_num . ' days', $today));
            $three_days_later_end = date('Y-m-d H:i:s', strtotime('+' . $before_days_end . ' days', $today));
            $subscribes = DB::table('course_subscribes')
                ->leftJoin('courses', 'course_subscribes.course_id', '=', 'courses.id')
                ->leftJoin('baby', 'course_subscribes.baby_id', '=', 'baby.id')
                ->leftJoin('wechat_users', 'baby.wechat_user_id', '=', 'wechat_users.id')
                ->where('courses.course_time', '>=', $three_days_later)
                ->where('courses.course_time', '<', $three_days_later_end)
                ->select(DB::raw('wechat_users.open_id,courses.course_time,courses.name as course_name, baby.name as baby_name, baby.guardian'))
                ->get();
            $app = new Application(config('wechat'));
            $notice = $app->notice;
            foreach ($subscribes as $sub) {
                $data = [
                    'first' => '您在悦宝上预约的课程将要开课了',
                    'keyword1' => $sub->course_name,
                    'keyword2' => $sub->course_time,
                    'keyword3' => '上海市闵行区华漕镇繁兴路399弄1号109-C婴智贝佳早教中心',
                    'remark' => '请按时上课哦',
                ];
                $msg_id[] = $notice->to($sub->open_id)->uses(Wechat::COURSE_TIME_REMINDER_TEMPLATE_ID)
                    ->addUrl(env('APP_URL'))
                    ->data($data)
                    ->send();
            }
        });
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}
